package xin.marcher.module.construction.repository;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.springframework.stereotype.Repository;
import xin.marcher.module.common.core.PageResult;
import xin.marcher.module.common.exception.CommonErrorCodeEnum;
import xin.marcher.module.common.exception.ProductBizException;
import xin.marcher.module.construction.converter.BuyerConverter;
import xin.marcher.module.construction.domain.dto.BuyerInfoDTO;
import xin.marcher.module.construction.domain.entity.BuyerInfoDO;
import xin.marcher.module.construction.domain.request.BuyerRequest;
import xin.marcher.module.construction.domain.request.QueryBuyerListRequest;
import xin.marcher.module.construction.domain.request.QueryBuyerPageRequest;
import xin.marcher.module.construction.mapper.BuyerInfoMapper;

import javax.annotation.Resource;
import java.util.List;
import java.util.Objects;

/**
 * 商品审核 资源管理
 */
@Repository
public class BuyerRepository {

    @Resource
    private BuyerConverter buyerConverter;

    @Resource
    private BuyerInfoMapper buyerInfoMapper;

    /**
     * 新增或者修改规格键信息
     *
     * @param buyerRequest
     * @return
     */
    public void saveOrUpdate(BuyerRequest buyerRequest) {
        if (Objects.isNull(buyerRequest.getId())) {
            save(buyerRequest);
        } else {
            update(buyerRequest);
        }
    }

    private void save(BuyerRequest buyerRequest) {
        BuyerInfoDO buyerInfoDO = buyerConverter.converterDO(buyerRequest);
        buyerInfoDO.initCommon();

        int count = buyerInfoMapper.insert(buyerInfoDO);
        if (count <= 0) {
            throw new ProductBizException(CommonErrorCodeEnum.SQL_ERROR);
        }
    }

    private void update(BuyerRequest buyerRequest) {
        buyerInfoMapper.updateById(buyerConverter.converterDO(buyerRequest));
    }

    /***
     *
     * @param queryBuyerListRequest
     * @return
     */
    public List<BuyerInfoDTO> listBuyerInfo(QueryBuyerListRequest queryBuyerListRequest) {
        LambdaQueryWrapper<BuyerInfoDO> queryWrapper = Wrappers.lambdaQuery();
        queryWrapper.in(BuyerInfoDO::getCategoryId, queryBuyerListRequest.getCategoryIdSet());
        return buyerConverter.converterDTOList(buyerInfoMapper.selectList(queryWrapper));
    }

    public PageResult<BuyerInfoDTO> pageResult(QueryBuyerPageRequest queryBuyerPageRequest) {

        LambdaQueryWrapper<BuyerInfoDO> queryWrapper = Wrappers.lambdaQuery();
        queryWrapper.like(BuyerInfoDO::getRoster, queryBuyerPageRequest.getRosterLike());
        Page<BuyerInfoDO> page = new Page<>(queryBuyerPageRequest.getPageNum(), queryBuyerPageRequest.getPageSize());
        Page<BuyerInfoDO> buyerInfoPage = buyerInfoMapper.selectPage(page, queryWrapper);

        return buyerConverter.converterPageResult(buyerInfoPage);
    }
}
